package lucene.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lucene.dao.IndexingGoodsDao;
import lucene.entity.*;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.solr.client.solrj.beans.Field;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.vacoor.nothing.common.util.Resources;
import org.vacoor.nothing.common.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.vacoor.nothing.security.lucene.SolrGoodsSearchServiceImpl.*;

/**
 * @author vacoor
 */
@Service
public class JiuSuIndexingServiceImpl extends GeneralIndexingServiceImpl {

    @Override
    protected Object toIndexedBean(IndexedGoods entity) {
        return GoodsIndexedBean.wrap(entity);
    }

    private static class GoodsIndexedBean {
        @Field
        private String id;  // 货品id
        @Field
        private String title;   // 货品标题
        @Field
        private String image;   // 货品图片
        @Field
        private String price;   // 货品价格
        @Field
        private String marketPrice; // 货品市场价
        @Field
        private Date putawayDate;   // 商家日期
        @Field
        private Long sales;         // 销量
        @Field("brand")
        private String brandId;     // 品牌id
        @Field("brandName")
        private String brandName;   // 品牌名称
        @Field("cat")
        private List<String> catIds = Lists.newArrayList(); // 分类id
        @Field("cat_*")
        private Map<String, String> catsAndParent = Maps.newHashMap();  // 分类名称及父分类
        @Field("props")
        private List<String> propKeys = Lists.newArrayList();   // 所有的属性
        @Field("prop_*")
        private Map<String, String> propAndValueMap = Maps.newHashMap();    // 所有的属性:属性值
        @Field("prop_v_*")
        private Map<String, String> propAndValueNames = Maps.newHashMap();  // 所有的属性和属性值名称
        @Field("pool")
        private String poolId;  // 商品池id
        @Field("model")
        private List<String> carBrandOrPlaceOrSeriesOrPowerOrModelIds = Lists.newArrayList();
        @Field("model_*")
        private Map<String, String> carBrandOrPlaceOrSeriesOrPowerOrModelNames = Maps.newHashMap();


        public static GoodsIndexedBean wrap(IndexedGoods goods) {
            return new GoodsIndexedBean(goods);
        }

        private GoodsIndexedBean(IndexedGoods goods) {
            if (null == goods) {
                throw new IllegalArgumentException("indexed goods must be not null");
            }
            id = goods.getId();
            title = goods.getTitle();
            title = StringUtils.hasText(title) ? title : goods.getProductTitle();
            List<String> images = goods.getImages();
            if (null != images && 0 < images.size()) {
                image = images.get(0);
            }
            price = goods.getPrice();
            marketPrice = goods.getMarketPrice();
            putawayDate = goods.getPutawayDate();
            sales = goods.getSales();   // 销量
            brandId = goods.getBrandId();
            brandName = goods.getBrandName();
            // 添加所有分类
            List<Cat> cats = goods.getCats();
            if (null != cats) {
                for (Cat cat : cats) {
                    for (; null != cat; cat = cat.getParent()) {
                        String catId = cat.getId();
                        String catName = cat.getName();
                        Cat p = cat.getParent();
                        String value = null == p ? catName : catName + MIX_VAL_DELIMITER + p.getId() + MIX_VAL_DELIMITER + p.getName();

                        catIds.add(catId);
                        catsAndParent.put(CAT_VAL_PREFIX + catId, value);
                    }
                }
            }
            List<PropVal> values = goods.getPropVals();
            if (!CollectionUtils.isEmpty(values)) {
                for (PropVal value : values) {
                    Prop prop = value.getProp();
                    if (null == prop) {
                        continue;
                    }

                    String sid = prop.getId();
                    String sname = prop.getName();
                    String vid = value.getId();
                    String firstValue = value.getFirstValue();
                    String secondValue = value.getSecondValue();

                    if (StringUtils.hasText(secondValue)) {
                        firstValue += "-" + secondValue;
                    }

                    propKeys.add(sid);
                    propAndValueMap.put(DYN_PROP_PREFIX + sid, vid);
                    propAndValueNames.put(DYN_PROP_VAL_PREFIX + vid, sname + "_" + firstValue);
                }
            }
            //

            poolId = goods.getPoolId();

            List<CarModel> models = goods.getModels();
            if (null != models) {
                // 为了去重
                for (CarModel model : models) {
                    CarSeries series = null == model ? null : model.getCarSeries();
                    CarPlace place = null == series ? null : series.getCarPlace();
                    CarBrand brand = null == place ? null : place.getCarBrand();

                    if (null == model || null == series || null == place || null == brand) {
                        continue;
                    }
                    // 车型品牌
                    String bid = brand.getId();
                    String bname = brand.getName();

                    carBrandOrPlaceOrSeriesOrPowerOrModelIds.add(bid);
                    carBrandOrPlaceOrSeriesOrPowerOrModelNames.put("model_" + bid, bname);

                    // 产地
                    String pid = place.getId();
                    String pname = bname + " " + place.getName();
                    carBrandOrPlaceOrSeriesOrPowerOrModelIds.add(pid);
                    carBrandOrPlaceOrSeriesOrPowerOrModelNames.put("model_" + pid, pname);

                    // 车系
                    String sid = series.getId();
                    String sname = pname + " " + series.getName();
                    carBrandOrPlaceOrSeriesOrPowerOrModelIds.add(sid);
                    carBrandOrPlaceOrSeriesOrPowerOrModelNames.put("model_" + sid, sname);

                    // 排量
                    String powerName = model.getPower();
                    String powerId = CarModel.encodePower(sid, powerName);
                    powerName = sname + " " + powerName;
                    carBrandOrPlaceOrSeriesOrPowerOrModelIds.add(powerId);
                    carBrandOrPlaceOrSeriesOrPowerOrModelNames.put("model_" + powerId, powerName);

                    // 车型
                    carBrandOrPlaceOrSeriesOrPowerOrModelIds.add(model.getId());
                    carBrandOrPlaceOrSeriesOrPowerOrModelNames.put("model_" + model.getId(), model.getName());
                }
            }
        }
    }

    public static void main(String[] args) {
        JiuSuIndexingServiceImpl indexing = new JiuSuIndexingServiceImpl();
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sf = builder.build(Resources.getResourceAsReader("mybatis-config.xml"));
        SqlSession session = sf.openSession();
        IndexingGoodsDao dao = session.getMapper(IndexingGoodsDao.class);

        indexing.setIndexingGoodsDao(dao);
        indexing.setSolrServer(new HttpSolrServer("http://112.124.123.60:8080/solr/jiusu"));
        indexing.rebuildIndex();
//        indexing.truncate();
    }
}
